package com.huluobo.hyj.hyjmodel.contract.register

import android.util.Log
import cn.bmob.v3.BmobUser
import cn.bmob.v3.exception.BmobException
import cn.bmob.v3.listener.SaveListener
import com.huluobo.hyj.hyjmodel.extention.isValidUserName
import com.huluobo.hyj.hyjmodel.extention.isValidUserPassword
import com.hyphenate.chat.EMClient
import com.hyphenate.exceptions.HyphenateException
import org.jetbrains.anko.doAsync

class RegisterPresenter(val view: RegisterContract.View):RegisterContract.Presenter {

    //注册
    override fun register(userName: String, password: String, ConfirmPassword: String) {
        if(userName.isValidUserName()){
            if(password.isValidUserPassword()){
                if(password == ConfirmPassword){
                    //账户密码无问题
                    view.onStartregister()
                    rigisterBmob(userName,password)
                }else view.onConfirmPasswordError()
            }else view.onPasswordError()
        }else view.onUserNameError()
    }

    private  fun rigisterBmob(userName: String,password: String){
        val bmobUser = BmobUser()
        bmobUser.username=userName
        bmobUser.setPassword(password)
        //注册到Bmob
        bmobUser.signUp(object : SaveListener<BmobUser>(){
            override fun done(bmobUser: BmobUser?, e: BmobException?) {
                if(e == null){
                    //注册成功
                    //注册到环信（公司流程）从服务器直接除恶到环信，返回给app注册成功
                    registerEaseMob(userName,password)
                }else
                    if (e.errorCode==208||e.errorCode==202){
                        runOnUiThread { view.onUserExist() }
                    Log.i("abc","done:${e}")
                }else{
                    //注册失败
                    runOnUiThread { view.onRegisterFailed("Bmob注册失败:" + e.errorCode.toString()) }
                    Log.i("abc","done:${e}")
                }
            }
        })
    }
    private fun registerEaseMob(userName: String,password: String){
        doAsync {//异步运行 运行在子线程
            try {//使用try和catch来返回成功或者失败
                EMClient.getInstance().createAccount(userName,password)//是同步方法
                //注册成功
                runOnUiThread { view.onRegisterSuccess() }
            }catch (e:HyphenateException){ //环信下的Exception异常
                Log.i("abc","huanxin:${e.errorCode},${e.message}")
                //注册失败
                runOnUiThread { view.onRegisterFailed("环信注册失败:" + e.message.toString()) }
            }
        }
    }
}